#include <QDir>
#include "recorder.h"

Recorder *Recorder::createRecorder(QObject *parent, const QString &savedName, const QString &savedPath)
{
    QVector<QString> oldRecords;
    QFile file(savedPath+"/"+savedName+".txt");
    if (file.exists() && file.open(QIODevice::ReadOnly | QIODevice::Text)){
        while (!file.atEnd()) {
            QByteArray line = file.readLine();
            oldRecords.push_back(QString::fromUtf8(line));
        }
        file.close();
    }

    Recorder* recorder = new Recorder(savedName,savedPath,parent);
    if(recorder->open()){
        recorder->m_records = oldRecords;
        return recorder;
    }else{
        delete recorder;
        return NULL;
    }
}

Recorder::Recorder(const QString &name, const QString &path, QObject *parent): QObject(parent)
{
    m_savedName = name;
    m_savedPath = path;
    m_file.setFileName(m_savedPath+"/"+m_savedName+".txt");
}


Recorder::~Recorder()
{
    if(m_file.isOpen()){
        m_file.close();
    }
}

/*
    返回当前记录数
*/
int Recorder::count()
{
    return m_records.size();
}

/*
    写一条记录。msg中不要有换行符，否则会影响readAll()
    读取
*/
void Recorder::write(const QString &msg)
{
    if(m_file.isOpen()){
        if(m_records.isEmpty()){
            m_file.write(msg.toUtf8());
        }else{
            m_file.write(("\n"+msg).toUtf8());
        }
        m_records.push_back(msg);
    }
}

/*
   返回所有记录
*/
const QVector<QString> &Recorder::read()
{
    return m_records;
}

/*
   清空记录
*/
void Recorder::flush()
{
    m_file.close();
    m_file.remove();
    m_records.clear();

    open();
}

bool Recorder::open()
{
    if(m_file.isOpen()){
        return true;
    }

    QDir dir(m_savedPath);
    if(!dir.exists()){
        if(!dir.mkpath(dir.absolutePath())){
            return false;
        }
    }

    return m_file.open(QFile::WriteOnly | QFile::Append);
}

void Recorder::close()
{
    if(m_file.isOpen()){
        m_file.close();
    }
}
